import { ControlType as TYPE } from "@components";
import { Button, Space, Spin, message } from "antd";
import { useMainContext } from '@contexts/MainContext'
import { useState, useRef } from "react";
import { RULE_REQUIRED } from "@rules";
import { findWeatherTypeGrade, findUnitRisks } from "@apis/indexApi";

const checkPrice = (_, value) => {
    const {subjectCountStart: Start, subjectCountEnd: End} = value
    // let IsEmpty = (Start ?? '') === '' || ( End ?? '') === ''
    // if ( IsEmpty ) {
    //   return Promise.reject(new Error('不允许为空!'));
    // }
    if (Start > End) {
      return Promise.reject(new Error('范围初始值不能大于结束值'));
    }
    return Promise.resolve();
};

const useFields = () => {

  const queryFormRef = useRef("queryFormRef");
  const modalFormRef = useRef("modalFormRef");
  const [WeatherTypes, setWeatherTypes] = useState([])
  const [unitRisks, setUnitRisks] = useState([])
  const [labelLoading, setLabelLoading] = useState(false)

  const findWeatherType = async (formRef) => {
      setWeatherTypes([])
      const weatherType = formRef.current?.getFieldValue('weatherType')
      if (!weatherType) return message.error('请先选择天气类型')

      setLabelLoading(true)
      const newWeatherTypes = await findWeatherTypeGrade({weatherType})
      setLabelLoading(false)
      setWeatherTypes(newWeatherTypes)
  }
  
  const getUnitRisks = async (formRef, row, setModalLoading) => {
    setUnitRisks([])
    const unitCode = formRef.current?.getFieldValue('unitCode')
    if (!unitCode) return message.error('请先选择机构')

    setLabelLoading(true)
    const newUnitRisks = await findUnitRisks(unitCode)
    setLabelLoading(false)
    setUnitRisks(newUnitRisks)

    if (!row) return
    const { productCodeList } = row
    const newValue = productCodeList?.length === newUnitRisks?.length ? ['all'] : productCodeList
    modalFormRef.current?.setFieldValue('untrueProductCodeList', newValue)
    setModalLoading(false)
  }

  const selectConfig = (name, label, codeKey) => {
    return {
      name,
      label,
      codeKey,
      controlType: TYPE.SELECT,
      allowClear: true,
      showSearch: true,
      optionFilterProp: "children",
      filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
      notFoundContent: labelLoading ? <Spin size="small" /> : null,
    }
  }

  const fields = [
    { 
      ...selectConfig('unitCode','归属机构','userAuthUnits'),
      onSelect: (value, option) => {
        if (!option?.value) return
        queryFormRef.current?.setFieldValue('productCode', null)
      },
      onClear: () => {
        queryFormRef.current?.setFieldValue('productCode', null)
      }
    }, 
    { 
      options: unitRisks,
      ...selectConfig('productCode','产品类型'),
      controlType: TYPE.SELECTBOTH,
      onFocus: () => getUnitRisks(queryFormRef)
    }, 
    { 
      ...selectConfig('weatherType','天气类型','WeatherType'),
      onSelect: (value, option) => {
        if (!option?.value) return
        queryFormRef.current?.setFieldsValue({ ...queryFormRef.current?.getFieldValue(), weatherTypeGrade: null })
      },
      onClear: () => {
        queryFormRef.current?.setFieldsValue({ ...queryFormRef.current?.getFieldValue(), weatherTypeGrade: null })
      }
    },
    { 
      options: WeatherTypes,
      ...selectConfig('weatherTypeGrade','天气类型等级'),
      onFocus: () => findWeatherType(queryFormRef)
    },
    { ...selectConfig('cfgRiskRank','风险等级','RiskGradeType') },
    { name: "createTime", label: "创建时间", controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ["createStartTime", "createEndTime"] },
    { name: "updateTime", label: "更新时间", controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ["updateStartTIme", "updateEndTime"] },
    { ...selectConfig("status","状态","status") },
  ];

  const modalFields = [
    { 
      ...selectConfig('unitCode','归属机构','userAuthUnits'),
      rules: [RULE_REQUIRED],
      onSelect: (value, option) => {
        if (!option?.value) return
        modalFormRef.current?.setFieldValue('productCode', null)
      },
      onClear: () => {
        modalFormRef.current?.setFieldValue('productCode', null)
      }
    }, 
    { 
      options: unitRisks,
      ...selectConfig('untrueProductCodeList','产品类型'),
      selectmode: "multiple",
      rules: [RULE_REQUIRED],
      controlType: TYPE.SELECTALL,
      onChange: (value, option=[]) => {
          modalFormRef.current?.setFieldValue('productCodeList', option.map(item => item.value))
          modalFormRef.current?.setFieldValue('productTypeList', option.map(item => item.children))
      },
      onFocus: () => getUnitRisks(modalFormRef)
  }, 
  { 
      options: [],
      ...selectConfig('productCodeList','产品类型'),
      selectmode: "multiple",
      mode: 'hidden'
  }, 
    { 
      ...selectConfig('productTypeList','产品类型Str'),
      selectmode: "multiple",
      mode: 'hidden'
    },
    { 
      ...selectConfig('weatherType','天气类型','WeatherType'),
      rules: [RULE_REQUIRED],
      onSelect: (value, option) => {
        if (!option?.value) return
        modalFormRef.current?.setFieldsValue({ ...modalFormRef.current?.getFieldValue(), weatherTypeGrade: null })
        setWeatherTypes([])
      },
    },
    { 
      options: WeatherTypes,
      ...selectConfig('weatherTypeGrade','天气类型等级'),
      rules: [RULE_REQUIRED],
      onFocus: () => findWeatherType(modalFormRef)
    },
    { ...selectConfig('cfgRiskRank','风险等级','RiskGradeType'), rules: [RULE_REQUIRED] },
    { name: 'subjectCountStart', label: '受灾数量(>=个)', controlType: TYPE.INPUT_NUMBER, controls:false, min: 1, rules: [RULE_REQUIRED] },
    { name: 'policyFeeStart', label: '总保额(>=万元)', controlType: TYPE.INPUT_NUMBER, controls:false },
    { name: 'policyAmountStart', label: '总保费(>=万元)', controlType: TYPE.INPUT_NUMBER, controls:false },
    { name: 'claimAmountStart', label: '理赔总费用', controlType: TYPE.INPUT_NUMBER, controls:false },
    { ...selectConfig("status","状态","status"), rules: [RULE_REQUIRED] },
  ];

  return {
    queryFormRef,
    fields,
    modalFormRef,
    modalFields,
    findWeatherType,
    getUnitRisks
  }
}

const GetColumns = ( edit ) => {
  const { isButtomShow } = useMainContext()

  return [
    { title: "归属机构", dataIndex: "unitName", key: "unitName", open: true, width: 100 },
    { title: "产品类型", dataIndex: "productTypeStr", key: "productTypeStr", open: true, width: 120 },
    { title: "天气类型", dataIndex: "weatherTypeName", key: "weatherTypeName", open: true, width: 100 },
    { title: '天气类型等级', dataIndex: 'weatherTypeGradeName', key: 'weatherTypeGradeName', open: true, width: 100 },
    { title: "风险等级", dataIndex: "cfgRiskRankName", key: "cfgRiskRankName", open: true, width: 100 },
    { title: "受灾标数量", dataIndex: "subjectCountStart", key: "subjectCountStart", open: true, width: 120 },
    { title: "创建时间", dataIndex: "createTime", key: "createTime", open: true, width: 120 },
    { title: "更新时间", dataIndex: "updateTime", key: "updateTime", open: true, width: 120 },
    { title: "状态", dataIndex: "statusName", key: "statusName", open: true, width: 100 },
    {
      title: "操作",
      dataIndex: "operationCol",
      key: "operationCol",
      open: true,
      width: 100,
      fixed: "right",
      render: (_, record) => {
        return (
          <Space>
            {isButtomShow('100103') && <Button type="primary" onClick={() => edit(record)}>
              编辑
            </Button>}
          </Space>
        );
      },
    },
  ];
};

export { useFields, GetColumns };
